package mcp

import (
	"fmt"

	"project-info/src/lib")

// 工具定义结构
type ToolDefinition struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	InputSchema map[string]interface{} `json:"inputSchema"`
	Handler     ToolHandler            `json:"-"` // 不序列化到JSON
}

// 工具处理器接口
type ToolHandler func(c *lib.GinContext, args map[string]interface{}) *MCPToolResult

// 工具管理器
type ToolsManager struct {
	tools map[string]*ToolDefinition
}

// 全局工具管理器实例
var GlobalToolsManager = NewToolsManager()

// 创建工具管理器
func NewToolsManager() *ToolsManager {
	tm := &ToolsManager{
		tools: make(map[string]*ToolDefinition),
	}

	// 注册所有工具
	tm.registerAllTools()
	return tm
}

// 注册所有工具
func (tm *ToolsManager) registerAllTools() {
	// GitLab相关工具
	tm.RegisterTool(&ToolDefinition{
		Name:        "list_gitlab_projects",
		Description: "列出GitLab项目",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"limit": map[string]interface{}{
					"type":        "integer",
					"description": "返回项目数量限制",
					"default":     10,
					"minimum":     1,
					"maximum":     100,
				},
				"search": map[string]interface{}{
					"type":        "string",
					"description": "搜索关键词",
					"required":    false,
				},
				"namespace": map[string]interface{}{
					"type":        "string",
					"description": "命名空间过滤",
					"required":    false,
				},
			},
		},
		Handler: handleListGitlabProjects,
	})

	tm.RegisterTool(&ToolDefinition{
		Name:        "search_gitlab_repos",
		Description: "搜索GitLab仓库",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"text": map[string]interface{}{
					"type":        "string",
					"description": "搜索文本",
					"required":    true,
				},
			},
			"required": []string{"text"},
		},
		Handler: handleSearchGitlabRepos,
	})

	// Jenkins相关工具
	tm.RegisterTool(&ToolDefinition{
		Name:        "get_jenkins_builds",
		Description: "获取Jenkins构建信息",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"app_name": map[string]interface{}{
					"type":        "string",
					"description": "应用名称",
					"default":     "",
					"required":    false,
				},
				"limit": map[string]interface{}{
					"type":        "integer",
					"description": "返回构建数量限制",
					"default":     5,
					"minimum":     1,
					"maximum":     50,
				},
				"status": map[string]interface{}{
					"type":        "string",
					"description": "构建状态过滤 (SUCCESS, FAILURE, BUILDING)",
					"enum":        []string{"SUCCESS", "FAILURE", "BUILDING", "ABORTED"},
				},
			},
		},
		Handler: handleGetJenkinsBuilds,
	})

	tm.RegisterTool(&ToolDefinition{
		Name:        "trigger_pipeline",
		Description: "触发Jenkins流水线构建",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"app_name": map[string]interface{}{
					"type":        "string",
					"description": "应用名称",
					"required":    true,
				},
				"branch": map[string]interface{}{
					"type":        "string",
					"description": "构建分支",
					"default":     "master",
				},
				"parameters": map[string]interface{}{
					"type":        "object",
					"description": "构建参数",
				},
			},
			"required": []string{"job_name"},
		},
		Handler: handleTriggerPipeline,
	})

	// 服务器管理工具
	tm.RegisterTool(&ToolDefinition{
		Name:        "get_server_list",
		Description: "获取服务器列表",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"limit": map[string]interface{}{
					"type":        "integer",
					"description": "返回服务器数量限制",
					"default":     10,
					"minimum":     1,
					"maximum":     100,
				},
				"os_type": map[string]interface{}{
					"type":        "string",
					"description": "操作系统类型过滤",
					"required":    false,
				},
			},
		},
		Handler: handleGetServerList,
	})

	// tm.RegisterTool(&ToolDefinition{
	// 	Name:        "ssh_execute_command",
	// 	Description: "在远程服务器上执行SSH命令",
	// 	InputSchema: map[string]interface{}{
	// 		"type": "object",
	// 		"properties": map[string]interface{}{
	// 			"server_id": map[string]interface{}{
	// 				"type":        "integer",
	// 				"description": "服务器ID",
	// 			},
	// 			"command": map[string]interface{}{
	// 				"type":        "string",
	// 				"description": "要执行的命令",
	// 			},
	// 			"timeout": map[string]interface{}{
	// 				"type":        "integer",
	// 				"description": "命令超时时间（秒）",
	// 				"default":     30,
	// 				"minimum":     1,
	// 				"maximum":     300,
	// 			},
	// 		},
	// 		"required": []string{"server_id", "command"},
	// 	},
	// 	Handler: handleSSHExecuteCommand,
	// })

	// 系统监控工具
	tm.RegisterTool(&ToolDefinition{
		Name:        "get_system_status",
		Description: "获取系统状态信息",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"detailed": map[string]interface{}{
					"type":        "boolean",
					"description": "是否返回详细信息",
					"default":     false,
				},
			},
		},
		Handler: handleGetSystemStatus,
	})

	// 工作流相关工具
	tm.RegisterTool(&ToolDefinition{
		Name:        "get_workflow_instances",
		Description: "获取工作流实例",
		InputSchema: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"status": map[string]interface{}{
					"type":        "string",
					"description": "工作流状态",
					"required":    false,
				},
				"limit": map[string]interface{}{
					"type":        "integer",
					"description": "返回数量限制",
					"default":     10,
				},
			},
		},
		Handler: handleGetWorkflowInstances,
	})
}

// 注册工具
func (tm *ToolsManager) RegisterTool(tool *ToolDefinition) {
	tm.tools[tool.Name] = tool
}

// 获取所有工具（用于MCP协议）
func (tm *ToolsManager) GetAllTools() []MCPTool {
	tools := make([]MCPTool, 0, len(tm.tools))
	for _, tool := range tm.tools {
		tools = append(tools, MCPTool{
			Name:        tool.Name,
			Description: tool.Description,
			InputSchema: tool.InputSchema,
		})
	}
	return tools
}

// 获取工具定义
func (tm *ToolsManager) GetTool(name string) (*ToolDefinition, bool) {
	tool, exists := tm.tools[name]
	return tool, exists
}

// 调用工具
func (tm *ToolsManager) CallTool(c *lib.GinContext, toolName string, args map[string]interface{}) *MCPToolResult {
	tool, exists := tm.GetTool(toolName)
	if !exists {
		return &MCPToolResult{
			Success: false,
			Error:   fmt.Sprintf("未知工具: %s", toolName),
		}
	}

	return tool.Handler(c, args)
}

// 获取工具列表（按分类）
func (tm *ToolsManager) GetToolsByCategory() map[string][]MCPTool {
	categories := map[string][]MCPTool{
		"GitLab":  {},
		"Jenkins": {},
		"服务器管理":   {},
		"系统监控":    {},
		"工作流":     {},
	}

	for _, tool := range tm.tools {
		mcpTool := MCPTool{
			Name:        tool.Name,
			Description: tool.Description,
			InputSchema: tool.InputSchema,
		}

		// 根据工具名称前缀分类
		switch {
		case contains(tool.Name, "gitlab"):
			categories["GitLab"] = append(categories["GitLab"], mcpTool)
		case contains(tool.Name, "jenkins") || contains(tool.Name, "pipeline"):
			categories["Jenkins"] = append(categories["Jenkins"], mcpTool)
		case contains(tool.Name, "server") || contains(tool.Name, "ssh"):
			categories["服务器管理"] = append(categories["服务器管理"], mcpTool)
		case contains(tool.Name, "system") || contains(tool.Name, "status"):
			categories["系统监控"] = append(categories["系统监控"], mcpTool)
		case contains(tool.Name, "workflow"):
			categories["工作流"] = append(categories["工作流"], mcpTool)
		default:
			categories["系统监控"] = append(categories["系统监控"], mcpTool)
		}
	}

	return categories
}

// 辅助函数
func contains(s, substr string) bool {
	return len(s) >= len(substr) && (s == substr ||
		(len(s) > len(substr) && (s[:len(substr)] == substr || s[len(s)-len(substr):] == substr ||
			containsSubstring(s, substr))))
}

func containsSubstring(s, substr string) bool {
	for i := 0; i <= len(s)-len(substr); i++ {
		if s[i:i+len(substr)] == substr {
			return true
		}
	}
	return false
}
